package pro.shuangxi.common.controller;

import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import pro.shuangxi.common.vo.Result;

import java.io.File;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.UUID;

/**
 * @author ：mengshx
 * @date ：Created in 2021/4/12 19:41
 * @description：文件服务器
 */
@Controller
public class FileController {
    @RequestMapping("/downloadFile.do")
    public ResponseEntity serveFile( String path) {
        try {
            path=URLDecoder.decode(path, "utf-8");
            Resource file = new FileSystemResource(path);
            return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,
                    "attachment; filename=\"" + file.getFilename() + "\"").body(file);
        } catch (Throwable e) {
            e.printStackTrace();
            return null;
        }
    }
    @RequestMapping("/uploadFile.do")
    @ResponseBody
    public Result handleFileUpload(@RequestParam("file") MultipartFile file, String path) {

        try {
            String filename = file.getOriginalFilename();
            filename = UUID.randomUUID().toString().substring(0,3)+"_"+filename;
            HashMap<String, String> response = new HashMap<>();
            file.transferTo(new File(path+File.separator+filename));
        } catch (Exception e) {
            return Result.error("上传失败");
        }
        return Result.error("上传成功");
    }
}
